package com.wing.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.request.ProductPackLabelForm;
import com.wing.order.dao.*;
import com.wing.order.model.entity.*;
import com.wing.order.model.request.OrderDeliveryForm;
import com.wing.order.model.response.OrderDeliveryDetailVO;
import com.wing.order.model.response.OrderDeliveryLabelVO;
import com.wing.order.model.response.OrderDeliveryVO;
import com.wing.order.model.response.ScanDeliveryVo;
import com.wing.platform.feign.PlatformClient;
import com.wing.platform.order.model.response.OrderDistributionLabelVO;
import com.wing.product.model.entity.ProductPackLabel;
import com.wing.product.service.ProductPackLabelService;
import com.wing.warehouse.model.response.PalletBoxListVO;
import com.wing.warehouse.service.PalletBoxListService;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 配送-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class OrderDeliveryServiceImpl extends ServiceImpl<OrderDeliveryDao, OrderDelivery> implements OrderDeliveryService {


    @Autowired
    private OrderDeliveryDetailService orderDeliveryDetailService;

    @Autowired
    private OrderDistributionLabelService orderDistributionLabelService;

    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private OrderDeliveryLabelService orderDeliveryLabelService;

    @Autowired
    private PlatformClient platformClient;

    @Autowired
    private OrderDeliveryDetailService deliveryDetailService;
    @Autowired
    private OrderDeliveryDetailDao orderDeliveryDetailDao;

    @Autowired
    private PalletBoxListService boxListService;
    @Autowired
    private OrderDeliverySignService signService;
    @Autowired
    private OrderDeliverySignDetailService signDetailService;

    @Autowired
    private ProductPackLabelService productPackLabelService;

    @Override
    public int add(OrderDeliveryForm orderDeliveryForm) {

        //校验

        OrderDelivery orderDelivery = new OrderDelivery();
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(OrderDelivery.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderDeliveryForm, orderDelivery, copyOptions);

        return baseMapper.insert(orderDelivery);
    }

    @Override
    public List<OrderDeliveryVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<OrderDeliveryVO> pageList4app(Page page, Map<String, Object> params) {
        List<OrderDeliveryVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public OrderDeliveryVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }


    @Override
    public Page<OrderDeliveryVO> stock(Page<OrderDeliveryVO> page, Map<String, Object> params) {
        List<OrderDeliveryVO> list = baseMapper.stock(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<OrderDeliveryDetailVO> stockInfo(String deliveryOrderCode) {
        List<OrderDeliveryDetailVO> stockInfo = baseMapper.stockInfo(deliveryOrderCode);

        return stockInfo;
    }

    @Override
    public Page<OrderDeliveryVO> finshInfo(Page<OrderDeliveryVO> page, Map<String, Object> params) {
        List<OrderDeliveryVO> list = baseMapper.finshInfo(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<OrderDeliveryVO> signProduct(String skuCode, String deliveryOrderCode) {
        return baseMapper.signProduct(skuCode, deliveryOrderCode);
    }


    @Override
    public Page<OrderDeliveryVO> infoSignList(Page<OrderDeliveryVO> page, Map<String, Object> params) {
        List<OrderDeliveryVO> list = baseMapper.infoSignList(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<OrderDeliveryVO> infoSign(String deliveryOrderCode) {
        return baseMapper.infoSign(deliveryOrderCode);
    }



    @Transactional
    @Override
    public JsonResult<OrderDeliveryVO> syncStorage( List<com.wing.platform.order.model.response.OrderDeliveryVO> list) {

        //将该批次的所有产品进行同步
        for (int i = 0; i <list.size() ; i++) {
            //配送明细
            OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
            orderDeliveryDetail.setId(null);
            orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.unfinished);
            orderDeliveryDetail.setSkuCode(list.get(i).getSkuCode());
            orderDeliveryDetail.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDeliveryDetail.setQuantityReceive(Long.valueOf(list.get(i).getQuantityReceive()));
            orderDeliveryDetail.setDeliveryId(Long.valueOf(list.get(i).getDeliveryId()));
            orderDeliveryDetail.setAbnormalNum(Long.valueOf(list.get(i).getAbnormalNum()));
            orderDeliveryDetailService.save(orderDeliveryDetail);
            OrderDistributionLabel orderDistributionLabel = new OrderDistributionLabel();

            //配货明细
            orderDistributionLabel.setId(null);
            orderDistributionLabel.setStatus(OrderDistributionLabel.Status.created);
            orderDistributionLabel.setSkuCode(list.get(i).getSkuCode());
            orderDistributionLabel.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDistributionLabel.setIsScan(true);
            orderDistributionLabelService.save(orderDistributionLabel);
            //产品包装条码
            com.wing.enterprise.order.model.ScanDeliveryVo scanDeliveryVo = new com.wing.enterprise.order.model.ScanDeliveryVo();
            scanDeliveryVo.setId(null);
            scanDeliveryVo.setSkuCode(list.get(i).getSkuCode());
            scanDeliveryVo.setPackLabelCode(list.get(i).getPackLabelCode());
            scanDeliveryVo.setRealReceive(list.get(i).getRealReceive());
            enterpriseClient.saveSign(scanDeliveryVo);
            //签收单扫描的包装条码
            OrderDeliveryLabel orderDeliveryLabel = new OrderDeliveryLabel();
            orderDeliveryLabel.setId(null);
            orderDeliveryLabel.setQuantity(Long.valueOf(list.get(i).getQuantityReceive()));
            // orderDeliveryLabel.setPackLabelId();
            orderDeliveryLabel.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDeliveryLabel.setPackId(Long.valueOf(list.get(i).getPackSpecId()));
            orderDeliveryLabel.setPackName(list.get(i).getPackSpecCode());
            orderDeliveryLabel.setDeliveryId(Long.valueOf(list.get(i).getDeliveryId()));
            orderDeliveryLabel.setDeliveryDetailId(Long.valueOf(list.get(i).getId()));
            orderDeliveryLabel.setSkuCode(list.get(i).getSkuCode());
            orderDeliveryLabel.setUnitName(list.get(i).getBaseUnitName());
            orderDeliveryLabelService.save(orderDeliveryLabel);
        }
        OrderDelivery delivery = this.getById(Long.valueOf(list.get(0).getDeliveryId()));
        if (delivery==null){
            //配送表
            OrderDelivery orderDelivery = new OrderDelivery();
            list.get(0).setSubmitTime(LocalDateTime.now().toString());
            BeanUtil.copyProperties(list.get(0),orderDelivery);
            orderDelivery.setId(Long.valueOf(list.get(0).getDeliveryId()));
            orderDelivery.setStatus(OrderDelivery.Status.signPart);
            orderDelivery.setSubmitTime(LocalDateTime.now());
            this.save(orderDelivery);
        }
        return JsonResult.success("同步成功！");
    }

    @Transactional
    @Override
    public JsonResult<ScanDeliveryVo> syncStorage(List<ScanDeliveryVo> list,String remark) {

        //将该批次的所有产品进行同步
        for (int i = 0; i <list.size() ; i++) {
            //配送明细
            OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
            orderDeliveryDetail.setId(null);
            orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.unfinished);
            orderDeliveryDetail.setSkuCode(list.get(i).getSkuCode());
            orderDeliveryDetail.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDeliveryDetail.setQuantityReceive(Long.valueOf(list.get(i).getQuantityReceive()));
            orderDeliveryDetail.setDeliveryId(Long.valueOf(list.get(i).getDeliveryId()));
            orderDeliveryDetail.setRemark(remark);
            orderDeliveryDetail.setPackSpecCode(list.get(i).getPackSpecCode());
            orderDeliveryDetail.setAbnormalNum(Long.valueOf(list.get(i).getAbnormalNum()));
            orderDeliveryDetailService.save(orderDeliveryDetail);
            OrderDistributionLabel orderDistributionLabel = new OrderDistributionLabel();

            //配货明细
            orderDistributionLabel.setId(null);
            orderDistributionLabel.setStatus(OrderDistributionLabel.Status.created);
            orderDistributionLabel.setSkuCode(list.get(i).getSkuCode());
            orderDistributionLabel.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDistributionLabel.setRealReceive(list.get(i).getRealReceive());
            orderDistributionLabel.setBaseUnitNum(list.get(i).getBaseunitNum());
            orderDistributionLabel.setPackLabelId(Long.valueOf(list.get(i).getPackLabelId()));
            orderDistributionLabel.setPackLabelCode(list.get(i).getPackLabelCode());
//            orderDistributionLabel.setIsScan(true);
            orderDistributionLabelService.save(orderDistributionLabel);
            //pro_product_pack_label 产品包装条码
            com.wing.enterprise.order.model.ScanDeliveryVo scanDeliveryVo = new com.wing.enterprise.order.model.ScanDeliveryVo();
            scanDeliveryVo.setId(null);
            scanDeliveryVo.setSkuCode(list.get(i).getSkuCode());
            scanDeliveryVo.setPackLabelCode(list.get(i).getPackLabelCode());
            scanDeliveryVo.setRealReceive(list.get(i).getRealReceive());
            enterpriseClient.saveSign(scanDeliveryVo);
        }
        //配送表
        OrderDelivery orderDelivery = new OrderDelivery();
        orderDelivery.setDeliveryOrderCode(list.get(0).getDeliveryOrderCode());
        orderDelivery.setId(Long.valueOf(list.get(0).getDeliveryId()));
        orderDelivery.setStatus(OrderDelivery.Status.sign);
        orderDelivery.setSigner(JwtUtils.getLoginUsername());
        orderDelivery.setSubmitTime(LocalDateTime.now());
        orderDelivery.setSignTime(LocalDateTime.now());
        orderDelivery.setSignCode(null);
        this.save(orderDelivery);


        return JsonResult.success("同步成功！");
    }

    @Override
    public Page<OrderDeliveryVO> pickupList(Page<OrderDeliveryVO> page, Map<String, Object> params) {
        List<OrderDeliveryVO> list = baseMapper.pickupList(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public List<OrderDeliveryDetailVO> pickupDetail(String deliveryOrderCode) {
        return baseMapper.pickupDetail(deliveryOrderCode);
    }

    @Override
    public List<OrderDeliveryVO> admSign(String deliveryOrderCode) {
        return null;
    }

    @Override
    public OrderDeliveryVO scanLable(String packLabelCode,String deliveryOrderCode) {
        return baseMapper.scanLable(packLabelCode,deliveryOrderCode);
    }


    @Override
    @Transactional
    public  List<ScanDeliveryVo>  signSubmit(List<ScanDeliveryVo> list) {
        if (list.size()==0){
            throw new BusinessException("无数据");
        }

        //根据传进来的配送表id查询企业端
        List<OrderDelivery> deliveryList=baseMapper.selectList(new QueryWrapper<OrderDelivery>().eq("id_platform",list.get(0).getDeliveryId()));
        //配送表
        OrderDelivery orderDelivery = new OrderDelivery();
        if (deliveryList.size()==0){
            orderDelivery.setDeliveryOrderCode(list.get(0).getDeliveryOrderCode());
            orderDelivery.setStatus(OrderDelivery.Status.signPart);
            orderDelivery.setSigner(JwtUtils.getLoginUsername());
            orderDelivery.setSubmitTime(LocalDateTime.now());
            orderDelivery.setSignTime(LocalDateTime.now());
            orderDelivery.setSigner(JwtUtils.getLoginUsername());
            orderDelivery.setSignTime(LocalDateTime.now());
            orderDelivery.setSignCode(null);
            orderDelivery.setIdPlatform(list.get(0).getDeliveryId());
            orderDelivery.setCreator(JwtUtils.getLoginUserId());
            orderDelivery.setCreatorName(JwtUtils.getLoginUsername());
            this.save(orderDelivery);
        }else{
            orderDelivery=deliveryList.get(0);
        }
        //将该批次的所有产品进行同步
        OrderDeliverySign orderDeliverySign =  new OrderDeliverySign();
        Map<String,Long> skuCodeDeliveryDetailIdMap=new HashMap<>();
        Map<String,Long> skuCodeSignDetailIdMap=new HashMap<>();
        for (int i = 0; i <list.size() ; i++) {
            list.get(0).setAbnormalNum(list.get(0).getQuantityReceive()-list.get(0).getRealReceive());
            QueryWrapper<OrderDeliveryDetail>detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("sku_code",list.get(i).getSkuCode());
            detailQueryWrapper.eq("delivery_id",orderDelivery.getId());
            OrderDeliveryDetail detail = orderDeliveryDetailService.getOne(detailQueryWrapper);
            //配送明细
//            OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
            if (detail==null){
                //配送明细
//                orderDeliveryDetail.setId(null);
                OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
                orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.finish);
                orderDeliveryDetail.setSkuCode(list.get(i).getSkuCode());
                orderDeliveryDetail.setPackLabelCode(list.get(i).getPackLabelCode());
                orderDeliveryDetail.setQuantityReceive(Long.valueOf(list.get(i).getQuantityReceive()));
                orderDeliveryDetail.setDeliveryId(orderDelivery.getId());
                orderDeliveryDetail.setIdPlatform(list.get(i).getId());
//                orderDeliveryDetail.setAbnormalNum(Long.valueOf(list.get(i).getQuantityReceive()-list.get(i).getRealReceive()));
                orderDeliveryDetail.setRemark(list.get(i).getRemark());
                //添加明细
                orderDeliveryDetailService.save(orderDeliveryDetail);
                skuCodeDeliveryDetailIdMap.put(list.get(i).getSkuCode(),orderDeliveryDetail.getId());
            }else{
                skuCodeDeliveryDetailIdMap.put(list.get(i).getSkuCode(),detail.getId());
            }
            if (i==0){
                Integer count=signService.count(new QueryWrapper<OrderDeliverySign>().eq("delivery_id",orderDelivery.getId()));
                orderDeliverySign.setCode(orderDelivery.getDeliveryOrderCode()+"-"+(count+1));
                orderDeliverySign.setStatus(OrderDeliverySign.Status.signed);
                orderDeliverySign.setDeliveryId(orderDelivery.getId());
                orderDeliverySign.setDeliveryDetailId(skuCodeDeliveryDetailIdMap.get(list.get(i).getSkuCode()));
                orderDeliverySign.setCreator(JwtUtils.getLoginUserId());
                orderDeliverySign.setCreatorName(JwtUtils.getLoginUsername());
                signService.save(orderDeliverySign);
            }
            if (!skuCodeSignDetailIdMap.containsKey(list.get(i).getSkuCode())){
                OrderDeliverySignDetail orderDeliverySignDetailSign = new OrderDeliverySignDetail();
                orderDeliverySignDetailSign.setSkuCode(list.get(i).getSkuCode());
                orderDeliverySignDetailSign.setQuantity(list.get(i).getRealReceive());
                orderDeliverySignDetailSign.setRemark(list.get(i).getRemark());
                orderDeliverySignDetailSign.setDeliveryId(orderDelivery.getId());
                orderDeliverySignDetailSign.setDeliveryDetailId(skuCodeDeliveryDetailIdMap.get(list.get(i).getSkuCode()));
                orderDeliverySignDetailSign.setSignId(orderDeliverySign.getId());
                signDetailService.save(orderDeliverySignDetailSign);
                skuCodeSignDetailIdMap.put(list.get(i).getSkuCode(),orderDeliverySignDetailSign.getId());
            }

            //签收单扫描的包装条码
            OrderDeliveryLabel orderDeliveryLabel = new OrderDeliveryLabel();
            orderDeliveryLabel.setPackLabelQuantity(Long.valueOf(list.get(i).getQuantityReceive()));
            orderDeliveryLabel.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDeliveryLabel.setPackId(Long.valueOf(list.get(i).getPackSpecId()));
            orderDeliveryLabel.setPackName(list.get(i).getPackSpecCode());
            orderDeliveryLabel.setDeliveryId(orderDelivery.getId());
            orderDeliveryLabel.setDeliveryDetailId(skuCodeDeliveryDetailIdMap.get(list.get(i).getSkuCode()));
            orderDeliveryLabel.setSkuCode(list.get(i).getSkuCode());
            orderDeliveryLabel.setUnitName(list.get(i).getBaseUnitName());
            orderDeliveryLabel.setAbnormalNum(list.get(i).getQuantityReceive()-list.get(i).getRealReceive());
            orderDeliveryLabel.setSignId(orderDeliverySign.getId());
            orderDeliveryLabel.setSignDetailId(skuCodeSignDetailIdMap.get(list.get(i).getSkuCode()));
            orderDeliveryLabel.setQuantity(Long.valueOf(list.get(i).getRealReceive()));
            orderDeliveryLabel.setStatus(OrderDeliveryLabel.Status.signed);
            orderDeliveryLabel.setCreatorName(JwtUtils.getLoginUsername());

            orderDeliveryLabelService.save(orderDeliveryLabel);
            //修改平台端详情的异常数
            platformClient.upDeliveryDetail(list.get(i).getId(),list.get(i).getAbnormalNum());
            //配货明细
            //修改平台端签收数量
            platformClient.upRealReceive(list.get(i).getPackLabelCode(),list.get(i).getDeliveryId(),list.get(i).getRealReceive());
            //产品包装条码
                com.wing.enterprise.order.model.ScanDeliveryVo scanDeliveryVo = new com.wing.enterprise.order.model.ScanDeliveryVo();
                scanDeliveryVo.setId(null);
                scanDeliveryVo.setSkuCode(list.get(i).getSkuCode());
                scanDeliveryVo.setPackLabelCode(list.get(i).getPackLabelCode());
                scanDeliveryVo.setRealReceive(list.get(i).getRealReceive());
                scanDeliveryVo.setBatchCode(list.get(0).getBatchCode());

                enterpriseClient.saveSign(scanDeliveryVo);
        }
        //修改明细状态
        //平台端
        Set<String> skuCodeSet=skuCodeDeliveryDetailIdMap.keySet();

        for (int i = 0; i <skuCodeSet.size() ; i++) {
            String skuCode=skuCodeSet.iterator().next();
            int num = platformClient.isSignProduct(list.get(i).getDeliveryOrderCode(),skuCode );
            //企业端
            int num2= baseMapper.isSignProduct(list.get(i).getDeliveryOrderCode(), skuCode);
            //表示平台端的产品已签收完/同步企业端
            if (num == num2){
                //修改平台端的状态
                platformClient.upDetail(list.get(i).getId());
//                platformClient.upDetail(list.get(i).getDeliveryId());
                //修改企业端状态
                OrderDeliveryDetail detail = new OrderDeliveryDetail();
//                detail.setStatus(OrderDeliveryDetail.Status.finish);
                detail.setStatus(OrderDeliveryDetail.Status.sign);
                detail.setId(list.get(i).getId());
                orderDeliveryDetailService.updateById(detail);
            }
        }
        //查询签收单下所有的包装码
        List<com.wing.platform.order.model.response.OrderDeliveryVO> info = platformClient.orderLableInfo(list.get(0).getDeliveryOrderCode());

        //判断签收单下所有的包装条码是否全部同步到企业端，则签收完成
        if (info.size() == baseMapper.getNum(list.get(0).getDeliveryOrderCode())){
            QueryWrapper<OrderDelivery> deliveryQueryWrapper = new QueryWrapper<>();
            deliveryQueryWrapper.eq("id_platform", info.get(0).getDeliveryId());
            OrderDelivery orderDelivery4Update = this.getOne(deliveryQueryWrapper);
            orderDelivery4Update.setStatus(OrderDelivery.Status.sign);
            baseMapper.updateById(orderDelivery4Update);
            //修改平台端配送表状态
            platformClient.upDelivery(info.get(0).getDeliveryId());
        }
        return list;
    }

     @Override
    @Transactional
    public  List<ScanDeliveryVo>  signSubmit2(List<ScanDeliveryVo> list) {
        if (list.size()==0){
            throw new BusinessException("无数据");
        }

        //根据传进来的配送表id查询企业端
        List<OrderDelivery> deliveryList=baseMapper.selectList(new QueryWrapper<OrderDelivery>().eq("id_platform",list.get(0).getDeliveryId()));
        //配送表
        OrderDelivery orderDelivery = new OrderDelivery();
        if (deliveryList.size()==0){
            orderDelivery.setDeliveryOrderCode(list.get(0).getDeliveryOrderCode());
            orderDelivery.setStatus(OrderDelivery.Status.signPart);
            orderDelivery.setSigner(JwtUtils.getLoginUsername());
            orderDelivery.setSubmitTime(LocalDateTime.now());
            orderDelivery.setSignTime(LocalDateTime.now());
            orderDelivery.setSigner(JwtUtils.getLoginUsername());
            orderDelivery.setSignTime(LocalDateTime.now());
            orderDelivery.setSignCode(null);
            orderDelivery.setIdPlatform(list.get(0).getDeliveryId());
            orderDelivery.setCreator(JwtUtils.getLoginUserId());
            orderDelivery.setCreatorName(JwtUtils.getLoginUsername());
            this.save(orderDelivery);
        }else{
            orderDelivery=deliveryList.get(0);
        }
        //将该批次的所有产品进行同步
        OrderDeliverySign orderDeliverySign =  new OrderDeliverySign();
        Map<String,Long> skuCodeDeliveryDetailIdMap=new HashMap<>();
        Map<String,Long> skuCodeSignDetailIdMap=new HashMap<>();
        for (int i = 0; i <list.size() ; i++) {
            list.get(0).setAbnormalNum(list.get(0).getQuantityReceive()-list.get(0).getRealReceive());
            QueryWrapper<OrderDeliveryDetail>detailQueryWrapper = new QueryWrapper<>();
            detailQueryWrapper.eq("sku_code",list.get(i).getSkuCode());
            detailQueryWrapper.eq("delivery_id",orderDelivery.getId());
            OrderDeliveryDetail detail = orderDeliveryDetailService.getOne(detailQueryWrapper);
            //配送明细
//            OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
            if (detail==null){
                //配送明细
//                orderDeliveryDetail.setId(null);
                OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
                orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.finish);
                orderDeliveryDetail.setSkuCode(list.get(i).getSkuCode());
                orderDeliveryDetail.setPackLabelCode(list.get(i).getPackLabelCode());
                orderDeliveryDetail.setQuantityReceive(Long.valueOf(list.get(i).getQuantityReceive()));
                orderDeliveryDetail.setDeliveryId(orderDelivery.getId());
                orderDeliveryDetail.setIdPlatform(list.get(i).getId());
//                orderDeliveryDetail.setAbnormalNum(Long.valueOf(list.get(i).getQuantityReceive()-list.get(i).getRealReceive()));
                orderDeliveryDetail.setRemark(list.get(i).getRemark());
                //添加明细
                orderDeliveryDetailService.save(orderDeliveryDetail);
                skuCodeDeliveryDetailIdMap.put(list.get(i).getSkuCode(),orderDeliveryDetail.getId());
            }else{
                skuCodeDeliveryDetailIdMap.put(list.get(i).getSkuCode(),detail.getId());
            }
            if (i==0){
                Integer count=signService.count(new QueryWrapper<OrderDeliverySign>().eq("delivery_id",orderDelivery.getId()));
                orderDeliverySign.setCode(orderDelivery.getDeliveryOrderCode()+"-"+(count+1));
                orderDeliverySign.setStatus(OrderDeliverySign.Status.signed);
                orderDeliverySign.setDeliveryId(orderDelivery.getId());
                orderDeliverySign.setDeliveryDetailId(skuCodeDeliveryDetailIdMap.get(list.get(i).getSkuCode()));
                orderDeliverySign.setCreator(JwtUtils.getLoginUserId());
                orderDeliverySign.setCreatorName(JwtUtils.getLoginUsername());
                signService.save(orderDeliverySign);
            }
            if (!skuCodeSignDetailIdMap.containsKey(list.get(i).getSkuCode())){
                OrderDeliverySignDetail orderDeliverySignDetailSign = new OrderDeliverySignDetail();
                orderDeliverySignDetailSign.setSkuCode(list.get(i).getSkuCode());
                orderDeliverySignDetailSign.setQuantity(list.get(i).getRealReceive());
                orderDeliverySignDetailSign.setRemark(list.get(i).getRemark());
                orderDeliverySignDetailSign.setDeliveryId(orderDelivery.getId());
                orderDeliverySignDetailSign.setDeliveryDetailId(skuCodeDeliveryDetailIdMap.get(list.get(i).getSkuCode()));
                orderDeliverySignDetailSign.setSignId(orderDeliverySign.getId());
                signDetailService.save(orderDeliverySignDetailSign);
                skuCodeSignDetailIdMap.put(list.get(i).getSkuCode(),orderDeliverySignDetailSign.getId());
            }

            //签收单扫描的包装条码
            OrderDeliveryLabel orderDeliveryLabel = new OrderDeliveryLabel();
            orderDeliveryLabel.setPackLabelQuantity(Long.valueOf(list.get(i).getQuantityReceive()));
            orderDeliveryLabel.setPackLabelCode(list.get(i).getPackLabelCode());
            orderDeliveryLabel.setPackId(Long.valueOf(list.get(i).getPackSpecId()));
            orderDeliveryLabel.setPackName(list.get(i).getPackSpecCode());
            orderDeliveryLabel.setDeliveryId(orderDelivery.getId());
            orderDeliveryLabel.setDeliveryDetailId(skuCodeDeliveryDetailIdMap.get(list.get(i).getSkuCode()));
            orderDeliveryLabel.setSkuCode(list.get(i).getSkuCode());
            orderDeliveryLabel.setUnitName(list.get(i).getBaseUnitName());
            orderDeliveryLabel.setAbnormalNum(list.get(i).getQuantityReceive()-list.get(i).getRealReceive());
            orderDeliveryLabel.setSignId(orderDeliverySign.getId());
            orderDeliveryLabel.setSignDetailId(skuCodeSignDetailIdMap.get(list.get(i).getSkuCode()));
            orderDeliveryLabel.setQuantity(Long.valueOf(list.get(i).getRealReceive()));
            orderDeliveryLabel.setStatus(OrderDeliveryLabel.Status.signed);
            orderDeliveryLabel.setCreatorName(JwtUtils.getLoginUsername());

            orderDeliveryLabelService.save(orderDeliveryLabel);
            //修改平台端详情的异常数
            platformClient.upAll("upAbnormalNum",list.get(i).getId(),list.get(i).getAbnormalNum(),"",0L,0);
            //配货明细
            //修改平台端签收数量
            platformClient.upAll("upRealReceive",0L,0,list.get(i).getPackLabelCode(),list.get(i).getDeliveryId(),list.get(i).getRealReceive());
            //产品包装条码
/*            com.wing.enterprise.order.model.ScanDeliveryVo scanDeliveryVo = new com.wing.enterprise.order.model.ScanDeliveryVo();
            scanDeliveryVo.setId(null);
            scanDeliveryVo.setSkuCode(list.get(i).getSkuCode());
            scanDeliveryVo.setPackLabelCode(list.get(i).getPackLabelCode());
            scanDeliveryVo.setRealReceive(list.get(i).getRealReceive());
            scanDeliveryVo.setBatchCode(list.get(0).getBatchCode());
            enterpriseClient.saveSign(scanDeliveryVo);*/
            ProductPackLabel productPackLabel = new ProductPackLabel();
            productPackLabel.setSurplusQuantity(list.get(i).getRealReceive());
            productPackLabel.setQuantity(list.get(i).getRealReceive());
            productPackLabel.setSkuCode(list.get(i).getSkuCode());
            productPackLabel.setBarcode(list.get(i).getPackLabelCode());
            productPackLabel.setCode(list.get(i).getPackLabelCode());
            productPackLabel.setBatchCode(list.get(0).getBatchCode());
            productPackLabelService.save(productPackLabel);
        }
        //修改明细状态
        //平台端
        Set<String> skuCodeSet=skuCodeDeliveryDetailIdMap.keySet();

        for (int i = 0; i <skuCodeSet.size() ; i++) {
            String skuCode=skuCodeSet.iterator().next();
            int num = platformClient.countNum("signNum",list.get(i).getDeliveryOrderCode(),skuCode );
            //企业端
            int num2= baseMapper.isSignProduct(list.get(i).getDeliveryOrderCode(), skuCode);
            //表示平台端的产品已签收完/同步企业端
            if (num == num2){
                //修改平台端的状态
                platformClient.upAll("upDeliveryDetail",list.get(i).getId(),0,"",0L,0);
//                platformClient.upDetail(list.get(i).getDeliveryId());
                //修改企业端状态
                OrderDeliveryDetail detail = new OrderDeliveryDetail();
//                detail.setStatus(OrderDeliveryDetail.Status.finish);
                detail.setStatus(OrderDeliveryDetail.Status.sign);
                detail.setId(list.get(i).getId());
                orderDeliveryDetailService.updateById(detail);
            }
        }
        //查询签收单下所有的包装码
        int info = platformClient.countNum("signAllNum", list.get(0).getDeliveryOrderCode(), "");

        //判断签收单下所有的包装条码是否全部同步到企业端，则签收完成
        if (info == baseMapper.getNum(list.get(0).getDeliveryOrderCode())){
            QueryWrapper<OrderDelivery> deliveryQueryWrapper = new QueryWrapper<>();
            deliveryQueryWrapper.eq("id_platform",  list.get(0).getDeliveryId());
            OrderDelivery orderDelivery4Update = this.getOne(deliveryQueryWrapper);
            orderDelivery4Update.setStatus(OrderDelivery.Status.sign);
            baseMapper.updateById(orderDelivery4Update);
            //修改平台端配送表状态
            platformClient.upAll("upDelivery",0L,0,"",list.get(0).getDeliveryId(),0);
        }
        return list;
    }



    @Override
    public int isSignProduct(String deliveryOrderCode, String skuCode) {
        return baseMapper.isSignProduct(deliveryOrderCode,skuCode);
    }

    @Override
    public int getNum(String deliveryOrderCode) {
        return baseMapper.getNum(deliveryOrderCode);
    }

    @Override
    public Integer countNotFinish(Long deliveryId) {
        return baseMapper.countNotFinish(deliveryId);
    }


    @Override
    @Transactional
    public void inventoryInSubmit(List<OrderDeliveryLabel> list) {

        Long deliveryId=null;
        for (OrderDeliveryLabel orderDeliveryLabel:list){

//            List<OrderDeliveryLabel> orderReceiveLabels=orderDeliveryLabelService.list(new QueryWrapper<OrderDeliveryLabel>().eq("delivery_detail_id",orderDeliveryLabel.getDeliveryDetailId()).eq("pack_label_code",orderDeliveryLabel.getPackLabelCode()));
            OrderDeliveryLabelVO orderDeliveryLabelDb=orderDeliveryLabelService.get4appById(orderDeliveryLabel.getId());
            if (deliveryId!=null&&deliveryId.equals(orderDeliveryLabelDb.getDeliveryId())){
                throw new BusinessException("条码不在一个签收单明细里面");
            }
            deliveryId=orderDeliveryLabelDb.getDeliveryId();
            if (orderDeliveryLabelDb==null){
                throw new BusinessException("未找到包装条码");
            }
            if (OrderDeliveryLabel.Status.inventoryIn.equals(orderDeliveryLabelDb.getStatus())){
                throw new BusinessException("此包装条码已入库");
            }

            if (orderDeliveryLabel.getQuantity()>orderDeliveryLabelDb.getQuantity()){
                throw new BusinessException("入库数量不能大于签收数量");
            }

            JsonResult<ProductPackLabelForm> jsonResult=enterpriseClient.extractPackLabel(orderDeliveryLabelDb.getPackLabelCode(),orderDeliveryLabel.getQuantity().intValue(),1);
            if (JsonResult.Code.SUCCESS.equals(jsonResult.getCode())){
                if (!orderDeliveryLabelDb.getQuantity().equals(orderDeliveryLabel.getQuantity())){
                    ProductPackLabelForm productPackLabelForm=jsonResult.getData();
                    OrderDeliveryLabel orderDeliveryLabel1=new OrderDeliveryLabel();
                    BeanUtils.copyProperties(orderDeliveryLabelDb,orderDeliveryLabel1);
                    orderDeliveryLabel1.setPackLabelCode(productPackLabelForm.getCode());
                    orderDeliveryLabel1.setPackLabelId(productPackLabelForm.getId());
                    orderDeliveryLabel1.setQuantity(orderDeliveryLabelDb.getQuantity()-orderDeliveryLabel.getQuantity());
                    orderDeliveryLabelService.save(orderDeliveryLabel1);
                }
            }else{
                throw new BusinessException(jsonResult.getMsg());
            }



            int count=deliveryDetailService.countNotFinish(orderDeliveryLabelDb.getDeliveryDetailId());
            if (count==0){
                OrderDeliveryDetail orderDeliveryDetail=new OrderDeliveryDetail();
                orderDeliveryDetail.setId(orderDeliveryLabelDb.getDeliveryDetailId());
                orderDeliveryDetail.setStatus(OrderDeliveryDetail.Status.finish);
                deliveryDetailService.updateById(orderDeliveryDetail);
            }

            PalletBoxListVO palletBoxListVO=boxListService.get4appById(orderDeliveryLabel.getBoxId());
            if (palletBoxListVO!=null){
                orderDeliveryLabel.setWarehouseId(palletBoxListVO.getWarehouseId());
                orderDeliveryLabel.setAreaId(palletBoxListVO.getAreaId());
                orderDeliveryLabel.setShelfId(palletBoxListVO.getShelfId());
                orderDeliveryLabel.setSpaceId(palletBoxListVO.getSpaceId());
            }
            orderDeliveryLabel.setId(orderDeliveryLabelDb.getId());
            orderDeliveryLabel.setStatus(OrderDeliveryLabel.Status.inventoryIn);
            orderDeliveryLabelService.updateById(orderDeliveryLabel);
        }

        int count=baseMapper.countNotFinish(deliveryId);
        if (count==0){
            OrderDelivery orderDelivery=new OrderDelivery();
            orderDelivery.setId(deliveryId);
            orderDelivery.setStatus(OrderDelivery.Status.inStorage);
            baseMapper.updateById(orderDelivery);
        }
    }
    @Transactional
    @Override
    public void deliverySign(List<OrderDistributionLabelVO> signList) {
        Long deliveryId = null;
        String deliveryOrderCode = "";
        Map<String,String> skuCodeMap = new HashMap<>();
        //查询平台端配送单信息
        OrderDelivery orderDelivery = new OrderDelivery();
        JsonResult<com.wing.platform.order.model.response.OrderDeliveryVO> deliveryJson = platformClient.getOrderDeliveryVOById(signList.get(0).getDeliveryId());
        //查询企业端配送单数据
        QueryWrapper<OrderDelivery> orderDeliveryQw = new QueryWrapper<>();
        orderDeliveryQw.eq("id_platform",signList.get(0).getDeliveryId());
        OrderDelivery delivery = baseMapper.selectOne(orderDeliveryQw);
        //企业端没有当前提交的配送单信息时添加
        if(delivery == null){
            orderDelivery.setDeliveryOrderCode(deliveryJson.getData().getDeliveryOrderCode());
            orderDelivery.setIdPlatform(deliveryJson.getData().getId());
            orderDelivery.setSignTime(LocalDateTime.now());
            orderDelivery.setSigner(JwtUtils.getLoginUsername());
            orderDelivery.setDistributionClerk(deliveryJson.getData().getDistributionClerk());
            if(deliveryJson.getData().getSkuNum() != null){
                orderDelivery.setSkuNum(deliveryJson.getData().getSkuNum().intValue());
            }
            orderDelivery.setCabNum(deliveryJson.getData().getCabNum());
            baseMapper.insert(orderDelivery);
            deliveryId = orderDelivery.getId();
            deliveryOrderCode = deliveryJson.getData().getDeliveryOrderCode();
            //查询平台端配送单明细
            JsonResult<List<com.wing.platform.order.model.entity.OrderDeliveryDetail>> DeliveryDetailJson = platformClient.getOrderDeliveryDetailVOById(signList.get(0).getDeliveryId());
            for (com.wing.platform.order.model.entity.OrderDeliveryDetail item : DeliveryDetailJson.getData()){
                OrderDeliveryDetail orderDeliveryDetail = new OrderDeliveryDetail();
                orderDeliveryDetail.setSkuCode(item.getSkuCode())
                        .setDeliveryId(deliveryId)
                        .setStatus(OrderDeliveryDetail.Status.unfinished)
                        .setIdPlatform(item.getId())
                        .setPlanReplenishment(item.getPlanReplenishment())
                        .setQuantityConfirm(item.getQuantityConfirm())
                        .setQuantityDistribute(item.getQuantityReceive());
                orderDeliveryDetailService.save(orderDeliveryDetail);
            }
        }else{
            deliveryId = delivery.getId();
            deliveryOrderCode = delivery.getDeliveryOrderCode();
        }

        //签收记录
        OrderDeliverySign orderDeliverySign = new OrderDeliverySign();
        Integer count = signService.count(new QueryWrapper<OrderDeliverySign>().eq("delivery_id",deliveryId));
        orderDeliverySign.setCode(deliveryOrderCode+"-"+(count+1))
                .setDeliveryId(deliveryId)
                .setCreatorName(JwtUtils.getLoginUsername());
        signService.save(orderDeliverySign);
        //签收包装码数据
        for (OrderDistributionLabelVO item : signList){
            QueryWrapper<OrderDeliveryDetail> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sku_code",item.getSkuCode()).eq("delivery_id",deliveryId);
            OrderDeliveryDetail detail = orderDeliveryDetailDao.selectOne(queryWrapper);
            //签收记录详情
            OrderDeliverySignDetail orderDeliverySignDetail = new OrderDeliverySignDetail();
            if(!skuCodeMap.containsKey(item.getSkuCode())){
                orderDeliverySignDetail.setCreatorName(JwtUtils.getLoginUsername())
                        .setSignId(orderDeliverySign.getId())
                        .setSkuCode(item.getSkuCode())
                        .setQuantity(item.getRealReceive().intValue())
                        .setDeliveryId(deliveryId)
                        .setDeliveryDetailId(detail.getId());
                signDetailService.save(orderDeliverySignDetail);
                skuCodeMap.put(item.getSkuCode(),item.getSkuCode());
            }

            //签收单扫描的包装条码
            OrderDeliveryLabel deliveryLabel = new OrderDeliveryLabel();
            deliveryLabel.setCreatorName(JwtUtils.getLoginUsername())
                    .setPackLabelQuantity(item.getRealReceive())
                    .setQuantity(item.getRealReceive())
                    .setPackLabelCode(item.getPackLabelCode())
                    .setPackName(item.getPackName())
                    .setDeliveryId(deliveryId)
                    .setDeliveryDetailId(detail.getId())
                    .setSkuCode(item.getSkuCode())
                    .setSignId(orderDeliverySign.getId())
                    .setSignDetailId(orderDeliverySignDetail.getId())
                    .setAbnormalNum(item.getAbnormalQuantity().intValue());
            orderDeliveryLabelService.save(deliveryLabel);
            //产品包装条码
            com.wing.enterprise.order.model.ScanDeliveryVo scanDeliveryVo = new com.wing.enterprise.order.model.ScanDeliveryVo();
            scanDeliveryVo.setId(null);
            scanDeliveryVo.setSkuCode(item.getSkuCode());
            scanDeliveryVo.setPackLabelCode(item.getPackLabelCode());
            scanDeliveryVo.setRealReceive(item.getRealReceive().intValue());
            scanDeliveryVo.setBatchCode(item.getBatchCode());
            enterpriseClient.saveSign(scanDeliveryVo);

        }
        JsonResult jsonResult = platformClient.deliverySign(signList);
        if (jsonResult.getCode() != Result.Code.SUCCESS.getCode()) {
            throw new BusinessException("签收失败");
        }
        //查询配送单包装码的总数和签收数，从平台查询
        JsonResult<Map> signSumJson = platformClient.getDeliverySignSum(signList.get(0).getDeliveryId());
        QueryWrapper<OrderDelivery> deliveryQw = new QueryWrapper<>();
        deliveryQw.eq("id_platform",signList.get(0).getDeliveryId());
        OrderDelivery info = baseMapper.selectOne(deliveryQw);
        Map data = signSumJson.getData();
        String signSum = data.get("signSum").toString();
        String total = data.get("total").toString();
        if(signSum.equals(total)){
            info.setStatus(OrderDelivery.Status.sign);
            baseMapper.updateById(info);
        }
        //查询配送单产品的包装条码总数和签收数
        QueryWrapper<OrderDeliveryDetail> deliveryDetailQw = new QueryWrapper<>();
        deliveryDetailQw.eq("delivery_id",info.getId());
        List<OrderDeliveryDetail> detailList = orderDeliveryDetailService.list(deliveryDetailQw);
        for (OrderDeliveryDetail item : detailList){
            JsonResult<Map> productSignSumMap = platformClient.getDeliveryProductSignSum(item.getIdPlatform());
            Map signSumMap = productSignSumMap.getData();
            String signProductSum = signSumMap.get("signProductSum").toString();
            String ProductTotal = signSumMap.get("ProductTotal").toString();
            if(signProductSum.equals(ProductTotal)){
                item.setStatus(OrderDeliveryDetail.Status.sign);
                orderDeliveryDetailDao.updateById(item);
            }
        }
    }


}

